from rest_framework.viewsets import ReadOnlyModelViewSet
from orders.models import OrderInfo
from meiduo_admin.serializers.orders import OrderSerialzier
from meiduo_admin.utils.pagination import MeiduoPagination
from rest_framework.decorators import action
from rest_framework.response import Response


class OrderView(ReadOnlyModelViewSet):
    # queryset =
    def get_queryset(self):
        # 基本查询
        queryset = OrderInfo.objects
        # 接收条件，进行查询
        keyword = self.request.query_params.get('keyword')
        if keyword:
            queryset = queryset.filter(order_id__contains=keyword)
        # 按创建时间降序，最新的订单显示在最前面
        queryset = queryset.order_by('-create_time')
        return queryset

    serializer_class = OrderSerialzier
    pagination_class = MeiduoPagination

    @action(methods=['put'], detail=True)  # orders/(?P<pk>\d+)/status/
    def status(self, request, *args, **kwargs):
        # 查询当前要修改的对象
        instance = self.get_object()  # GenericAPIView
        # 接收指定的状态
        status = request.data.get('status')
        # 修改
        instance.status = status
        instance.save()

        return Response({
            'order_id': instance.order_id,
            'status': instance.status
        })
